package edu.ccut.saturn.studio.authority.part;

import org.eclipse.jface.viewers.ICellModifier;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.widgets.TableItem;

import  edu.ccut.saturn.studio.authority.model.AuthorityModel;
import  edu.ccut.saturn.studio.authority.model.Resource;
import edu.ccut.saturn.studio.component.model.ComponentModel;


/**
 * 表格单元修改器
 * @author Bai Yucheng
 * 
 */
public class TableViewerCellModifier implements ICellModifier {
	private TableViewer tv;
	private AuthorityModel dm;

	public TableViewerCellModifier(TableViewer tv, AuthorityModel dm) {
		this.tv = tv;
		this.dm = dm;
	}

	public TableViewerCellModifier(TableViewer paramTableViewer,
			ComponentModel componentModel) {
		// TODO Auto-generated constructor stub
	}

	// 返回是否可以被修改，true为可修改
	public boolean canModify(Object element, String property) {
		return true;
	}

	// 返回列的值：参数element是表格记录的对象，property是表格列的属性
	public Object getValue(Object element, String property) {
		Resource resource = (Resource) element;
		if (property.equals("name")) {
			return String.valueOf(resource.getName());
		} 
		else if (property.equals("value")) {
			return String.valueOf(resource.getValue());
		} else if (property.equals("description")) {
			return String.valueOf(resource.getDescritpion());
		} else {
			return null;
		}
	}

	/**
	 * 修改表格单元中的值
	 * 
	 * @param element
	 *            表格记录的对象
	 * @param property
	 *            表格列的属性
	 * @param value
	 *            修改的新值
	 */
	public void modify(Object element, String property, Object value) {
		TableItem tableItem = (TableItem) element;
		Resource resource = (Resource) tableItem.getData();
		if (property.equals("name")) {
			String newValue = (String) value;
			if (newValue.equals("")) {
				return;
			} else {
				resource.setName(newValue);
			}
			dm.updateResourceAttribute(String.valueOf(resource.getId()), "name", newValue);
		}

		if (property.equals("value")) {
			String newValue = (String) value;
			if (newValue.equals("")) {
				return;
			} else {
				resource.setValue(newValue);
			}
			dm.updateResourceAttribute(String.valueOf(resource.getId()), "value", newValue);
		}
		if (property.equals("description")) {
			String newValue = (String) value;
			if (newValue.equals("")) {
				return;
			} else {
				resource.setDescritpion(newValue);
			}
			dm.updateResourceAttribute(String.valueOf(resource.getId()), "description", newValue);
		}

		// 修改更新
		tv.refresh();
	}
}